#!/bin/bash
# liwl@nsccwx
# 本部分练习计时器脚本
# bug:
## 1. 无法正确计算中文长度,导致退格失败
## 2. 无法正常显示倒计时,会多出0

# 倒计时显示
function timer(){
	local second=$1
	if [ $# -ne 1 ];then
		echo "call function:${FUNCNAME[0]} failed."
		echo "call function as ${FUNCNAME[0]} [second]."
		exit 0
	fi
	echo "设置倒计时秒数:${second}"
	read -p "是否开始计时(y/n):" ANSWER
	if [ "${ANSWER}" != 'y' ];then
		echo "退出"
		exit 0
	fi
	#获取输入描述的长度
	len_second=${#second}
	show_info="timer start:"
	len_back=$[${#show_info}+${len_second}]
	# 退格
	b='\b'	
	for i in $(seq 1 ${len_back})
	do
		b='\b'${b}
	done
	#显示
	local mytime=1
	while [ ${mytime} -le ${second} ]
	do
		#正计时
		#echo -ne "${show_info}${mytime}"
		#到计时
		echo -ne "${show_info}$[${second}+1-${mytime}]"
		echo -ne "${b}"
		sleep 1
		mytime=$[${mytime}+1]
	done
}
timer $1

